import org.apache.struts.action.*;
import org.apache.struts.util.MessageResources;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Locale;
import edu.harvard.eecs.airg.coloredtrails.controller.ControlImpl;

/**
 * Created by IntelliJ IDEA.
 * User: rani
 * Date: Feb 27, 2008
 * Time: 11:30:14 AM
 */
public class ConnectAction extends Action {

  public ActionForward execute(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response)
    throws IOException, ServletException {


    HttpSession session = request.getSession();
    DynaActionForm connectForm = (DynaActionForm) form;
    String action = request.getParameter("action");

    String address = (String) connectForm.get("address");
    String userIDs = (String) connectForm.get("userIDs");
    session.setAttribute("address", address);
    FormFile configFile = (FormFile) connectForm.get("configFile");


    System.out.println("CT controller address=" + address);
    System.out.println("User IDs=" + userIDs);
    byte[] configFileData = configFile.getFileData();
    String configFileName = configFile.toString();
    configFileName = configFileName.split(new String("\\."))[0];
    System.out.println("configFile =" + configFileName);

    ControlImpl controlImpl = new ControlImpl(address);
    controlImpl.sendConfig(configFileData, configFileName);
    controlImpl.newGame(configFileName, userIDs);
      

    if (mapping.getAttribute() != null) {

      if ("request".equals(mapping.getScope()))
        request.removeAttribute(mapping.getAttribute());
      else
        session.removeAttribute(mapping.getAttribute());
    }

    return (mapping.findForward("success"));
  }

}
